import { _decorator, Component, Node, Vec3, Camera, UITransform, view, math, TiledMap, director, Vec2 } from 'cc';
import EventManager from '../Base/EventManager';
const { ccclass, property } = _decorator;

@ccclass('CameraFollow')
export class CameraFollow extends Component {
    @property({ type: Node })
    target: Node = null;

    @property({ type: TiledMap })
    tileMap: TiledMap = null;

    @property({ type: Camera })
    uiCamera: Camera = null;

    @property
    OrthoHeight: number = 200;

    @property
    smoothTime: number = 0.1; // 平滑跟随系数

    private camera: Camera = null;
    private _mapWidth: number = 0;
    private _mapHeight: number = 0;
    private _currentVelocity = new Vec3();

    protected onLoad(): void {
        EventManager.Instance.on("PLAYER_CHUNK_CHANGED", this.setTileMap, this);
    }

    protected onDestroy(): void {
        EventManager.Instance.off("PLAYER_CHUNK_CHANGED", this.setTileMap); 
    }

    start() {
        this.camera = this.getComponent(Camera);

        this.camera.orthoHeight = this.OrthoHeight;
        this.uiCamera.orthoHeight = this.OrthoHeight;
    }

    setTileMap(data) {
        const { tileMap, pos } = data;
        console.log("setTileMap ->", tileMap.name);
        this.tileMap = tileMap;
        const uiTransform = this.tileMap.node.getComponent(UITransform);
        this._mapWidth = uiTransform.width;
        this._mapHeight = uiTransform.height;

    }

    lateUpdate(deltaTime: number) {
        if (!this.target || !this.tileMap) return;

        const targetPos = this.target.getPosition();
        const currentPos = this.node.getPosition();
        
        // 平滑阻尼移动
        const newPos = new Vec3();
        Vec3.lerp(newPos, currentPos, targetPos, Math.min(deltaTime / this.smoothTime, 1));
        
        // 约束相机边界
        this.clampCameraPosition(newPos);
        this.node.setPosition(newPos);
        this.uiCamera.node.setPosition(newPos);
    }

    private clampCameraPosition(pos: Vec3) {
        const visibleSize = view.getVisibleSize();
        const aspectRatio = visibleSize.width / visibleSize.height;
        const viewportHeight = this.camera.orthoHeight * 2;
        const viewportWidth = viewportHeight * aspectRatio;
        
        // 当前地图块的世界位置
        const mapPos = this.tileMap.node.position;
        
        // 计算基于地图块世界坐标的边界
        const minX = mapPos.x - this._mapWidth / 2 + viewportWidth / 2;
        const maxX = mapPos.x + this._mapWidth / 2 - viewportWidth / 2;
        const minY = mapPos.y - this._mapHeight / 2 + viewportHeight / 2;
        const maxY = mapPos.y + this._mapHeight / 2 - viewportHeight / 2;

        pos.x = math.clamp(pos.x, minX, maxX);
        pos.y = math.clamp(pos.y, minY, maxY);
    }
}